"""序列化工具模块

提供 PersistentLoginInfo 的序列化/反序列化支持
"""

import json
from datetime import datetime
from typing import Dict, Any

from ..base.models import PersistentLoginInfo


def persistent_info_to_dict(info: PersistentLoginInfo) -> Dict[str, Any]:
    """将 PersistentLoginInfo 转换为字典
    
    Args:
        info: PersistentLoginInfo 实例
        
    Returns:
        Dict[str, Any]: 可序列化的字典
    """
    return info.to_dict()


def persistent_info_from_dict(data: Dict[str, Any]) -> PersistentLoginInfo:
    """从字典创建 PersistentLoginInfo
    
    Args:
        data: 字典数据
        
    Returns:
        PersistentLoginInfo: PersistentLoginInfo 实例
    """
    return PersistentLoginInfo.from_dict(data)


def persistent_info_to_json(info: PersistentLoginInfo, indent: int = None) -> str:
    """将 PersistentLoginInfo 转换为 JSON 字符串
    
    Args:
        info: PersistentLoginInfo 实例
        indent: JSON 缩进，None 表示紧凑格式
        
    Returns:
        str: JSON 字符串
    """
    return json.dumps(persistent_info_to_dict(info), indent=indent, ensure_ascii=False)


def persistent_info_from_json(json_str: str) -> PersistentLoginInfo:
    """从 JSON 字符串创建 PersistentLoginInfo
    
    Args:
        json_str: JSON 字符串
        
    Returns:
        PersistentLoginInfo: PersistentLoginInfo 实例
    """
    data = json.loads(json_str)
    return persistent_info_from_dict(data)


def save_persistent_info_to_file(info: PersistentLoginInfo, file_path: str, indent: int = None) -> None:
    """将 PersistentLoginInfo 保存到文件
    
    Args:
        info: PersistentLoginInfo 实例
        file_path: 文件路径
        indent: JSON 缩进，None 表示紧凑格式
    """
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(persistent_info_to_json(info, indent))


def load_persistent_info_from_file(file_path: str) -> PersistentLoginInfo:
    """从文件加载 PersistentLoginInfo
    
    Args:
        file_path: 文件路径
        
    Returns:
        PersistentLoginInfo: PersistentLoginInfo 实例
    """
    with open(file_path, "r", encoding="utf-8") as f:
        json_str = f.read()
    return persistent_info_from_json(json_str)